<template>
  <div class="app-container">
    <div class="custom_card_0" v-show="showSearch">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="isAvailable">
        <el-select v-model="queryParams.isAvailable" placeholder="请选择是否启用" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_available"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </div>
    <div class="custom_card">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['plan:rule:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange" border>
      <el-table-column label="标题" align="center" prop="title"/>
<!--      <el-table-column label="起租天数" align="center" prop="startingLeaseDays"/>-->
      <el-table-column label="包含非时间段租期" align="center" prop="diintplt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.business_yes_no" :value="scope.row.diintplt"/>
        </template>
      </el-table-column>
      <el-table-column label="时间段" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}~{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="门店" align="center" prop="remark" min-width="180" show-overflow-tooltip/>

      <el-table-column label="是否启用" align="center" prop="isAvailable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_available" :value="scope.row.isAvailable"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"/>

      <el-table-column label="操作" align="center" fixed="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleAvailable(scope.row.id,1)" v-hasPermi="['plan:rule:edit']" v-if="scope.row.isAvailable ==0">启用</el-button>
          <el-button size="mini" type="text" @click="handleAvailable(scope.row.id,0)" v-hasPermi="['plan:rule:edit']" v-if="scope.row.isAvailable ==1">停用</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['plan:rule:edit']" v-if="scope.row.isAvailable ==0">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)" v-hasPermi="['plan:rule:remove']" v-if="scope.row.isAvailable ==0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </div>
    <!-- 添加或修改起租规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-form ref="form" class="rule-form" :model="form" :rules="rules" label-width="180px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" maxlength="20" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规定起租天数的时间段" prop="timeSlot">
              <el-date-picker clearable v-model="form.timeSlot" size="small" style="width: 300px;"  value-format="yyyy-MM-dd"
                              :picker-options="pickerOptions"
                              type="daterange"  range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间" >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isAvailable">
              <el-radio-group v-model="form.isAvailable">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否包含非时间段租期" prop="diintplt">
              <el-tooltip placement="top" effect="dark" style="    margin-left: -20px;">
                <div slot="content" style="font-size: 13px">
                  ①是:客户租期满足起租天数，即可下单<br/>
                  ②否:客户租期与规定起租天数时段的交集，需交集时间满足起租天数，才能下单
                </div>
                <el-button type="text"><i class="el-icon-warning-outline"></i></el-button>
              </el-tooltip>
              <el-radio-group v-model="form.diintplt">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>





        <el-divider content-position="center">起租规则门店信息</el-divider>
        <div  style="margin: 0 100px">
          <el-table :data="planStartingLeaseStoreList" ref="planStartingLeaseStore" border>
            <el-table-column width="50"  prop="selected" align="center">
              <template slot="header" slot-scope="scope">
                <el-checkbox v-model="selectAll"></el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.selected"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="门店" prop="storeName" align="center"/>
            <el-table-column label="起租天数" prop="startingLeaseDays" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.startingLeaseDays" :disabled="!scope.row.selected"

                          @keyup.native="scope.row.startingLeaseDays =minOne( oninput(scope.row.startingLeaseDays, 0))"
                          placeholder="请输入起租天数" style="width: 200px"/>
              </template>
            </el-table-column>
          </el-table>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listRule, getRule, delRule, addRule, updateRule, getAllEuleStoreList , editAvailable} from "@/api/plan/rule";

export default {
  name: "Rule",
  dicts: ['sys_available', 'business_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedPlanStartingLeaseStore: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      selectAll: false,
      // 总条数
      total: 0,
      // 起租规则表格数据
      ruleList: [],
      // 起租规则门店表格数据
      planStartingLeaseStoreList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        startTime: null,
        endTime: null,
        startingLeaseDays: null,
        diintplt: null,
        isAvailable: null,
      },
      pickerOptions: {
        // disabledDate是一个函数,参数是当前选中的日期值,这个函数需要返回一个Boolean值,
        disabledDate: (time) => {
          // 如果函数处理比较简单,可以直接在这里写逻辑方法
          return time.getTime() < Date.now()
        }
      },
      // 表单参数
      form: {
        timeSlot:[],
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
        ],
        timeSlot: [
          { required: true, message: '规定起租天数的时间段不能为空', trigger: 'blur' },
        ],
        startingLeaseDays: [
          { required: true, message: '起租天数不能为空', trigger: 'blur' },
        ],
        diintplt: [
          { required: true, message: '是否包含非时间段租期', trigger: 'blur' },
        ],
        isAvailable: [
          { required: true, message: '是否启用', trigger: 'blur' },
        ],
      }
    };
  },
  watch: {
    selectAll: {
      immediate: true,
      handler(val) {
        this.planStartingLeaseStoreList.forEach(item=>{
          item.selected = val
        })
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    minOne(num){
      return Number(num)<1?1:num
    },
    /** 查询起租规则列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then(response => {
        this.ruleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        startTime: null,
        endTime: null,
        startingLeaseDays: null,
        diintplt: 1,
        delFlag: null,
        isAvailable: 1,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId: null,
        tenantId: null,
        timeSlot: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getAllEuleStoreList(ruleId){
      getAllEuleStoreList(ruleId).then(res=>{
        this.planStartingLeaseStoreList = res.data;
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getAllEuleStoreList(-1)
      this.open = true;
      this.title = "添加起租规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRule(id).then(response => {
        this.form = {
          ...response.data,
          timeSlot:[]
        };
        this.form.timeSlot.push(this.form.startTime)
        this.form.timeSlot.push(this.form.endTime)
        this.open = true;
        this.title = "修改起租规则";
      });
      this.getAllEuleStoreList(id)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

         let planStartingLeaseStoreList =  this.planStartingLeaseStoreList.filter(item=> item.selected);
         for (let item of planStartingLeaseStoreList){
           if(!item.startingLeaseDays&&item.startingLeaseDays!==0){
             this.$modal.msgError("请输入起租天数");
            return;
           }
         }
          let data = {
            ...this.form,
            planStartingLeaseStoreList:planStartingLeaseStoreList,
            startTime:this.form.timeSlot[0],
            endTime:this.form.timeSlot[1],
          }
          if (this.form.id != null) {
            updateRule(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRule(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 启用/停用 */
    handleAvailable(id, available) {
      this.$modal.confirm('是否确认'+(available===1?'启用':'停用')+'起租规则？').then(function () {
        return editAvailable({
          id: id,
          isAvailable: available,
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除起租规则？').then(function () {
        return delRule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>
<style scoped>
::v-deep .rule-form .el-form-item--medium .el-form-item__content{
  width: 300px;
}
</style>
